<template>
  <div class="page-container">
    <div class="page-header">
      <h1>租赁记录管理</h1>
      <el-button type="primary" @click="handleRefresh" :icon="Refresh">
        刷新数据
      </el-button>
    </div>

    <div class="content-card">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" class="search-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="客户姓名">
                <el-input
                  v-model="searchForm.customerName"
                  placeholder="请输入客户姓名"
                  clearable
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="车牌号">
                <el-input
                  v-model="searchForm.plateNumber"
                  placeholder="请输入车牌号"
                  clearable
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="租赁状态">
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                  <el-option label="全部" value="" />
                  <el-option label="已拒绝" value="-1" />
                  <el-option label="待审核" value="0" />
                  <el-option label="进行中" value="1" />
                  <el-option label="已完成" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" @click="handleSearch" :loading="searching" :icon="Search">
                  搜索
                </el-button>
                <el-button @click="handleReset" :icon="Refresh">
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 租赁记录列表 -->
      <div class="table-section">
        <el-table
          :data="rentalList"
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无租赁记录"
          @row-click="handleRowClick"
          class="rental-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="id" label="租赁ID" width="100" align="center" />
          <el-table-column prop="customerName" label="客户姓名" min-width="120" show-overflow-tooltip />
          <el-table-column prop="carInfo" label="车辆信息" min-width="200" show-overflow-tooltip />
          <el-table-column prop="startRentalTime" label="开始日期" min-width="120" align="center" />
          <el-table-column prop="endRentalTime" label="结束日期" min-width="120" align="center" />
          <el-table-column prop="realReturnTime" label="实际归还" min-width="120" align="center">
            <template #default="scope">
              {{ scope.row.realReturnTime || '未归还' }}
            </template>
          </el-table-column>
          <el-table-column prop="money" label="总金额" width="120" align="center">
            <template #default="scope">
              <span class="money-text">¥{{ scope.row.money }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status, scope.row.realReturnTime)" size="small">
                {{ getStatusText(scope.row.status, scope.row.realReturnTime) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click.stop="handleViewDetail(scope.row)"
                :icon="View"
                circle
                title="查看详情"
              />
              <el-button
                v-if="scope.row.status == 1 && !scope.row.realReturnTime"
                size="small"
                type="warning"
                @click.stop="handleReturn(scope.row)"
                :icon="Edit"
                circle
                title="办理归还"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 租赁详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="租赁记录详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="selectedRental" class="rental-detail">
        <!-- 基本信息 -->
        <el-descriptions title="租赁信息" :column="2" border>
          <el-descriptions-item label="租赁ID">{{ selectedRental.id }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ selectedRental.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户手机">{{ selectedRental.phone }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ selectedRental.cartNumber || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="车辆信息" :span="2">{{ selectedRental.carInfo }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ selectedRental.startRentalTime }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ selectedRental.endRentalTime }}</el-descriptions-item>
          <el-descriptions-item label="实际归还">{{ selectedRental.realReturnTime || '未归还' }}</el-descriptions-item>
          <el-descriptions-item label="客户ID">{{ selectedRental.customerId }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ selectedRental.money }}</el-descriptions-item>
          <el-descriptions-item label="租赁状态">
            <el-tag :type="getStatusType(selectedRental.status, selectedRental.realReturnTime)">
              {{ getStatusText(selectedRental.status, selectedRental.realReturnTime) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="车辆ID">{{ selectedRental.carId }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 归还车辆对话框 -->
    <el-dialog
      v-model="returnDialogVisible"
      title="办理车辆归还"
      width="500px"
      :before-close="handleReturnDialogClose"
    >
      <el-form
        ref="returnFormRef"
        :model="returnForm"
        :rules="returnRules"
        label-width="120px"
        class="return-form"
      >
        <el-form-item label="客户姓名">
          <el-input v-model="returnForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="车辆信息">
          <el-input v-model="returnForm.carInfo" disabled />
        </el-form-item>
        <el-form-item label="实际归还日期" prop="actualReturnDate">
          <el-date-picker
            v-model="returnForm.actualReturnDate"
            type="date"
            placeholder="选择实际归还日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="增加的里程数" prop="mileage">
          <el-input-number
            v-model="returnForm.mileage"
            :min="0"
            style="width: 100%"
            placeholder="请输入增加的里程数"
          />
        </el-form-item>
        <el-form-item label="车辆状况" prop="condition">
          <el-select
            v-model="returnForm.condition"
            placeholder="请选择车辆状况"
            style="width: 100%"
          >
            <el-option label="良好" value="良好" />
            <el-option label="需要维修" value="需要维修" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="损坏原因"
          prop="damageDescription"
          v-if="returnForm.condition === '需要维修'"
        >
          <el-input
            v-model="returnForm.damageDescription"
            type="textarea"
            :rows="3"
            placeholder="请描述车辆损坏原因"
          />
        </el-form-item>
        <el-form-item
          label="维修金额"
          prop="repairCost"
          v-if="returnForm.condition === '需要维修'"
        >
          <el-input-number
            v-model="returnForm.repairCost"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入维修金额"
          />
        </el-form-item>
        <el-form-item
          label="维修人员"
          prop="technicianId"
          v-if="returnForm.condition === '需要维修'"
        >
          <el-select
            v-model="returnForm.technicianId"
            placeholder="请选择维修人员"
            style="width: 100%"
          >
            <el-option
              v-for="tech in technicianOptions"
              :key="tech.id"
              :label="tech.name"
              :value="tech.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleReturnDialogClose">取消</el-button>
          <el-button type="primary" @click="handleConfirmReturn" :loading="returningCar">
            确认归还
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, View, Edit } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const searching = ref(false)
const detailDialogVisible = ref(false)
const returnDialogVisible = ref(false)
const returningCar = ref(false)

// 选中的租赁记录
const selectedRental = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const rentalList = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  plateNumber: '',
  status: ''
})

// 归还表单
const returnForm = reactive({
  id: null,
  carId: null,
  customerName: '',
  carInfo: '',
  actualReturnDate: '',
  mileage: 0,
  condition: '良好',
  damageDescription: '',
  repairCost: 0,
  technicianId: null
})

// 维修人员选项
const technicianOptions = ref([])

// 表单引用
const returnFormRef = ref(null)

// 归还表单验证规则
const returnRules = {
  actualReturnDate: [
    { required: true, message: '请选择实际归还日期', trigger: 'change' }
  ],
  mileage: [
    { required: true, message: '请输入增加的里程数', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择车辆状况', trigger: 'change' }
  ],
  damageDescription: [
    { required: true, message: '请描述车辆损坏原因', trigger: 'blur' }
  ],
  repairCost: [
    { required: true, message: '请输入维修金额', trigger: 'blur' }
  ],
  technicianId: [
    { required: true, message: '请选择维修人员', trigger: 'change' }
  ]
}

// 获取租赁记录列表
const fetchRentalList = async (isSearch = false) => {
  try {
    if (isSearch) {
      searching.value = true
    } else {
      loading.value = true
    }

    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    // 构建查询参数
    const params = new URLSearchParams({
      page: currentPage.value,
      size: pageSize.value
    })

    // 添加搜索条件
    if (searchForm.customerName) params.append('customerName', searchForm.customerName)
    if (searchForm.plateNumber) params.append('plateNumber', searchForm.plateNumber)
    if (searchForm.status) params.append('status', searchForm.status)

    const url = `http://localhost:8080/rental/list?${params.toString()}`
    console.log('获取租赁记录列表，请求URL:', url)

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    console.log('获取租赁记录列表响应:', result)

    if (result.code === 200) {
      rentalList.value = result.data.records || []
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10

      if (isSearch && rentalList.value.length === 0) {
        ElMessage.info('未找到符合条件的租赁记录')
      }
    } else {
      ElMessage.error(result.message || '获取租赁记录列表失败')
    }
  } catch (error) {
    console.error('获取租赁记录列表错误:', error)
    ElMessage.error('获取租赁记录列表失败，请检查网络连接')
  } finally {
    loading.value = false
    searching.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchRentalList(true)
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    plateNumber: '',
    status: ''
  })
  currentPage.value = 1
  fetchRentalList()
}

// 刷新数据
const handleRefresh = () => {
  fetchRentalList()
}

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRentalList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchRentalList()
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 查看详情
const handleViewDetail = (rental) => {
  selectedRental.value = rental
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedRental.value = null
}



// 办理归还
const handleReturn = (rental) => {
  // 填充归还表单数据
  returnForm.id = rental.id
  returnForm.carId = rental.carId
  returnForm.customerName = rental.customerName
  returnForm.carInfo = rental.carInfo
  returnForm.actualReturnDate = ''
  returnForm.mileage = 0
  returnForm.condition = '良好'
  returnForm.damageDescription = ''
  returnForm.repairCost = 0
  returnForm.technicianId = null

  returnDialogVisible.value = true
}

// 关闭归还对话框
const handleReturnDialogClose = () => {
  returnDialogVisible.value = false
  resetReturnForm()
  if (returnFormRef.value) {
    returnFormRef.value.clearValidate()
  }
}

// 重置归还表单
const resetReturnForm = () => {
  Object.assign(returnForm, {
    id: null,
    carId: null,
    customerName: '',
    carInfo: '',
    actualReturnDate: '',
    mileage: 0,
    condition: '良好',
    damageDescription: '',
    repairCost: 0,
    technicianId: null
  })
}

// 确认归还
const handleConfirmReturn = async () => {
  if (!returnFormRef.value) return

  await returnFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        returningCar.value = true
        const token = localStorage.getItem('Token')
        if (!token) {
          ElMessage.error('未登录或登录已过期')
          return
        }

        // 构建请求URL - 使用与管理员端相同的API
        const updateStatusUrl = new URL(`http://localhost:8080/car/updateStatus/${returnForm.carId}`)

        // 根据车辆状况设置不同的状态值
        updateStatusUrl.searchParams.append('status', returnForm.condition === '良好' ? '2' : '3')
        updateStatusUrl.searchParams.append('mileage', returnForm.mileage)
        updateStatusUrl.searchParams.append('returnTime', returnForm.actualReturnDate)

        // 如果车辆需要维修，添加维修相关信息
        if (returnForm.condition === '需要维修') {
          updateStatusUrl.searchParams.append('repairReason', returnForm.damageDescription)
          updateStatusUrl.searchParams.append('repairMoney', returnForm.repairCost)
          // 直接使用选中的维修人员姓名（因为ID就是姓名）
          if (returnForm.technicianId) {
            updateStatusUrl.searchParams.append('employeeName', returnForm.technicianId)
          }
        }

        console.log('办理归还，请求URL:', updateStatusUrl.toString())

        const response = await fetch(updateStatusUrl, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          }
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`更新车辆状态失败: ${response.status}`)
        }

        const result = await response.json()
        console.log('办理归还响应:', result)

        if (result.code === 200) {
          ElMessage.success('车辆归还办理成功！')
          returnDialogVisible.value = false
          resetReturnForm()
          fetchRentalList()
        } else {
          throw new Error(result.message || '更新车辆状态失败')
        }
      } catch (error) {
        console.error('办理归还错误:', error)
        ElMessage.error('办理归还失败：' + error.message)
      } finally {
        returningCar.value = false
      }
    }
  })
}

// 工具函数
const getStatusType = (status, realReturnTime) => {
  // 如果状态为进行中(1)且有实际归还时间，则为维修中
  if (status == 1 && realReturnTime) {
    return 'warning'  // 维修中用橙色
  }

  const statusTypeMap = {
    '-1': 'danger',   // 已拒绝
    0: 'warning',     // 待审核
    1: 'primary',     // 进行中
    2: 'success'      // 已完成
  }
  return statusTypeMap[status] || 'info'
}

const getStatusText = (status, realReturnTime) => {
  // 如果状态为进行中(1)且有实际归还时间，则显示为维修中
  if (status == 1 && realReturnTime) {
    return '维修中'
  }

  const statusMap = {
    '-1': '已拒绝',
    0: '待审核',
    1: '进行中',
    2: '已完成'
  }
  return statusMap[status] || '未知'
}

// 获取维修人员列表
const fetchTechnicians = async () => {
  try {
    const token = localStorage.getItem('Token')
    if (!token) return

    const response = await fetch('http://localhost:8080/employee/names', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.ok) {
      const result = await response.json()
      console.log('获取维修人员列表响应:', result)
      if (result.code === 200) {
        // 将字符串数组转换为对象数组，以便在下拉框中使用
        technicianOptions.value = (result.data || []).map((name) => ({
          id: name,    // 使用姓名作为ID
          name: name   // 姓名
        }))
      }
    }
  } catch (error) {
    console.error('获取维修人员列表失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRentalList()
  fetchTechnicians()
})
</script>

<style scoped>
@import '../employee/employee-common.css';

.money-text {
  font-weight: 600;
  color: #e6a23c;
}

.rental-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.rental-table .el-table__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.rental-table .el-table__header th {
  background: transparent !important;
  color: white !important;
  font-weight: 600;
  border: none !important;
}

.rental-table .el-table__row {
  transition: all 0.2s ease;
  cursor: pointer;
}

.rental-table .el-table__row:hover {
  background-color: rgba(102, 126, 234, 0.05) !important;
}
</style>
